# 注册与登录接口
from django.http import JsonResponse
from django import forms
from django.forms import model_to_dict



from web.models import Users
from web import utils


tools = utils.Utils()

class LoginForm(forms.ModelForm):
    class Meta:
        model = Users
        fields = ['account', 'password', 'avatar']

# 返回用户数据格式
def user_data_format(user):
    new_user = model_to_dict(user)

    # 时间
    new_user['create_time'] = tools.time_format(user.create_time)
    new_user['update_time'] = tools.time_format(user.update_time)

    # 头像
    if user.avatar:
        new_user['avatar'] = user.avatar.url
    else:
        new_user['avatar'] = '/media/user/avatar/default.jpg'

    # 删除密码
    del new_user['password']

    return new_user

# 注册
def register(request):
    if request.method == 'POST':
        form = LoginForm(request.POST, files=request.FILES)
        try:
            if form.is_valid():

                form.save()
                user = user_data_format(form.instance)
                return JsonResponse(tools.Response(200, '注册成功', user))
            else:
                error = tools.Forms_GetError(form)
                return JsonResponse(tools.Response(400, f'注册失败: {error}'))
        except Exception as e:
            return JsonResponse(tools.Response(400, f'{e}'))
    else:
        return JsonResponse(tools.Response(405, '请求方法错误'))

# 登录
def login(request):
    if request.method == 'POST':
        account = request.POST.get('account')
        password = request.POST.get('password')
        if not account or not password:
            return JsonResponse(tools.Response(400, '账号或密码不能为空'))

        # 查询用户
        user = Users.objects.filter(account=account, password=password).first()
        if not user:
            return JsonResponse(tools.Response(400, '账号不存在'))

        form = LoginForm(request.POST, instance=user)
        if form.is_valid():
            user = user_data_format(form.instance)
            return JsonResponse(tools.Response(200, '登录成功', user))
        else:
            error = tools.Forms_GetError(form)
            return JsonResponse(tools.Response(400, f'登录失败: {error}'))
    else:
        return JsonResponse(tools.Response(405, '请求方法错误'))

